﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using xnaGraphics = Microsoft.Xna.Framework.Graphics;
using xna = Microsoft.Xna.Framework;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;

namespace client.app.gui2
{
    /// <summary>
    /// MapUI.xaml 的交互逻辑
    /// </summary>
    public partial class MapUI : UserControl, IUICanvas, IUInput
    {
        #region Block
        public class Block : ContentControl, IUInput
        {
            static Polygon MakePath(List<int[]> pathList)
            {
                var points = new PointCollection();
                foreach (var item in pathList)
                {
                    points.Add(new Point(item[0], item[1]));
                }
                return new Polygon { Points = points };
            }
            static List<int[]> _iconLayout = new List<int[]>();
            static Block()
            {
                _iconLayout.Add(new int[] { 15, 22, 0 });
                _iconLayout.Add(new int[] { 11, 16, 30 });
                _iconLayout.Add(new int[] { 9, 13, 50 });
            }

            public bool StopEvent
            {
                get { return true; }
            }

            public int BlockX { get; private set; }
            public int BlockY { get; private set; }
            public xna.Vector2 Position { get; private set; }
            public xna.Vector2 Centre { get; private set; }

            public string SpaceId { get; private set; }
            public comm.objst.SpaceInfo SpaceInfo { get; private set; }

            comm.objst.DStar.Data.Space _space = null;
            MapUI _mapUI = null;
            TextBlock _tbHoverName = null;
            Polygon _fillPath = null;

            public Block(MapUI mapUI, int blockX, int blockY, comm.objst.DStar.Data.Space space)
            {
                _mapUI = mapUI;
                _space = space;
                SpaceId = space.SpaceId;
                BlockX = blockX;
                BlockY = blockY;

                #region minX, minY, maxX, maxY
                int minX = -1, minY = -1, maxX = 0, maxY = 0;
                foreach (var dot in _space.PathList)
                {
                    if (minX == -1)
                    {
                        minX = dot[0];
                        minY = dot[1];
                    }
                    minX = Math.Min(minX, dot[0]);
                    minY = Math.Min(minY, dot[1]);

                    maxX = Math.Max(maxX, dot[0]);
                    maxY = Math.Max(maxY, dot[1]);
                }
                int pathX = minX, pathY = minY, pathWidth = maxX - minX, pathHeight = maxY - minY;
                #endregion

                Position = new xna.Vector2(pathX, pathY);
                Centre = new xna.Vector2(_space.CentreX, _space.CentreY);

                #region Relative PathList
                var relativePathList = new List<int[]>();
                foreach (var dot in _space.PathList)
                {
                    relativePathList.Add(new int[] { dot[0] - minX, dot[1] - minY });
                }
                var path = MakePath(relativePathList);
                path.Stroke = new SolidColorBrush(Color2.Yellow());
                path.StrokeThickness = 1;
                var cv = new Canvas
                {
                    Width = pathWidth,
                    Height = pathHeight,
                    Margin = new Thickness(4)
                };
                cv.Children.Add(path);
                _mapUI._cacheBlock.AddElement(_space.SpaceId, cv);
                #endregion

                #region _tbHoverName
                _tbHoverName = new TextBlock
                {
                    Text = "N/A",
                    Foreground = new SolidColorBrush(Color2.Yellow())
                };
                _mapUI._cacheName.AddElement(_space.SpaceId, new Border
                {
                    Child = _tbHoverName,
                    Margin = new Thickness(0, 0, 4, 4)
                });
                #endregion

                _fillPath = MakePath(space.PathList);
                _fillPath.Fill = new SolidColorBrush(Color2.Black(30));
                _mapUI.GetLayer(LAYER_FILL).Children.Add(_fillPath);

                var strokePath = MakePath(space.PathList);
                strokePath.Stroke = new SolidColorBrush(Color2.Black(50));
                _mapUI.GetLayer(LAYER_STROKE).Children.Add(strokePath);

                var cvRoot = new Canvas();
                var maskPath = MakePath(space.PathList);
                maskPath.Fill = new SolidColorBrush(Color2.Transparent());
                cvRoot.Children.Add(maskPath);

                Content = cvRoot;
            }

            void LayoutPeople(comm.objst.SpaceInfo spaceInfo)
            {
                var sp = new StackPanel
                {
                    Orientation = Orientation.Horizontal
                };
                double width = 0;
                if (spaceInfo.State == comm.objst.SpaceState.WAR_IN)
                {
                    #region fire
                    var img = new Image
                    {
                        Source = _mapUI._bitmapFire,
                        Width = _mapUI._bitmapFire.PixelWidth,
                        Height = _mapUI._bitmapFire.PixelHeight
                    };
                    img.SetLeftTop(_space.CentreX - img.Width / 2, _space.CentreY - img.Height / 2);
                    _mapUI.GetLayer(LAYER_FIRE).Children.Add(img);
                    #endregion

                    var dirs = new string[] { "right", "left", "left", "right" };
                    for (int i = 0, len = spaceInfo.HeroStatList.Count; i < len; i++)
                    {
                        var item = spaceInfo.HeroStatList[i];
                        var icon = MakeIcons(item.FactionId, item.HeroCount, dirs[i]);
                        width += icon.Width;
                        if (i == 2)
                        {
                            sp.Children.Insert(0, icon);
                        }
                        else
                        {
                            sp.Children.Add(icon);
                        }
                    }
                }
                else
                {
                    var dir = "left";
                    if (_space.CentreX > _mapUI.cvLayer.Width / 2)
                    {
                        dir = "right";
                    }
                    foreach (var item in spaceInfo.HeroStatList)
                    {
                        var icon = MakeIcons(item.FactionId, item.HeroCount, dir);
                        width += icon.Width;
                        sp.Children.Add(icon);
                    }
                }

                sp.Width = width;

                var x = _space.CentreX - sp.Width / 2;
                if (x < 0)
                {
                    x += 2;
                }
                else if (x + sp.Width > _mapUI.cvLayer.Width)
                {
                    x -= 2;
                }
                sp.SetLeftTop(x, _space.CentreY);
                _mapUI.GetLayer(LAYER_PEOPLE).Children.Add(sp);
            }
            StackPanel MakeIcons(string factionId, int count, string dir = "left")
            {
                var id = int.Parse(MainGame.MainSpace.DStar.ToRawId(factionId));
                double i1 = 10d, i2 = 5d;
                var c1 = (int)Math.Floor(count / i1);
                var c2 = (int)Math.Floor((count - c1 * i1) / i2);
                var c3 = count - c1 * i1 - c2 * i2;
                double width = 0;
                var sp = new StackPanel
                {
                    Orientation = Orientation.Horizontal
                };
                if (c1 > 0)
                {
                    for (int i = 0; i < c1; i++)
                    {
                        var icon = MakeIcon(0, id, c1);
                        width += icon.Width;
                        if (dir == "left")
                        {
                            sp.Children.Add(icon);
                        }
                        else
                        {
                            sp.Children.Insert(0, icon);
                        }
                    }
                }
                if (c2 > 0)
                {
                    var icon = MakeIcon(1, id, c2);
                    width += icon.Width;
                    if (dir == "left")
                    {
                        sp.Children.Add(icon);
                    }
                    else
                    {
                        sp.Children.Insert(0, icon);
                    }
                }
                if (c3 > 0)
                {
                    for (int i = 0; i < c3; i++)
                    {
                        var icon = MakeIcon(2, id, (int)c3);
                        width += icon.Width;
                        if (dir == "left")
                        {
                            sp.Children.Add(icon);
                        }
                        else
                        {
                            sp.Children.Insert(0, icon);
                        }
                    }
                }
                sp.Width = width;
                return sp;
            }
            Canvas MakeIcon(int index, int id, int count)
            {
                var layout = _iconLayout[index];
                var cv = new Canvas
                {
                    Width = layout[0],
                    Height = layout[1],
                    VerticalAlignment = VerticalAlignment.Bottom
                };
                cv.Clip = new RectangleGeometry(new Rect(0, 0, cv.Width, cv.Height));
                var img = new Image
                {
                    Source = _mapUI._bitmapPeople,
                    Width = _mapUI._bitmapPeople.PixelWidth,
                    Height = _mapUI._bitmapPeople.PixelHeight
                };
                img.SetLeftTop(-layout[0] * id, -layout[2]);
                cv.Children.Add(img);
                return cv;
            }

            public void FillSpaceInfo(comm.objst.SpaceInfo spaceInfo)
            {
                SpaceInfo = spaceInfo;

                _tbHoverName.Text = spaceInfo.Name;

                var facInfo = MainGame.MainSpace.GetFactionInfo(spaceInfo.FactionId);
                if (facInfo != null)
                {
                    var color = Color.FromRgb(facInfo.Color.R, facInfo.Color.G, facInfo.Color.B);
                    _fillPath.Fill = new SolidColorBrush(Color2.FromColor(255 / 100 * 30, color));
                }

                //spaceInfo.State = comm.objst.SpaceState.WAR_IN;
                //spaceInfo.HeroStatList.Add(new comm.objst.SpaceHeroStat { FactionId = "1001", HeroCount = 100 });

                LayoutPeople(spaceInfo);

                if (spaceInfo.OccupyType == comm.objst.SpaceOccupyType.MONSTER)
                {
                    #region monster
                    var img = new Image
                    {
                        Source = _mapUI._bitmapMonster,
                        Width = _mapUI._bitmapMonster.PixelWidth,
                        Height = _mapUI._bitmapMonster.PixelHeight
                    };
                    img.SetLeftTop(_space.CentreX - img.Width / 2, _space.CentreY - img.Height / 2);
                    _mapUI.GetLayer(LAYER_FLAG).Children.Add(img);
                    _tbHoverName.Text += "(怪物控制)";
                    #endregion
                }
                if (spaceInfo.State == comm.objst.SpaceState.NOT_OPEN)
                {
                    _fillPath.Fill = new SolidColorBrush(Color2.White(10));
                    _tbHoverName.Text += "(未开放)";
                }
            }
            public void CallMouseEvent(MouseEventType type, Point point)
            {
                _mapUI.BlockMouseEvent(type, point, this);
            }
            public void Draw(xnaGraphics.SpriteBatch spriteBatch)
            {
                if (SpaceInfo != null && SpaceInfo.DisplayFlag)
                {
                    MainGame.MainWindow.DrawCacheTex(spriteBatch, MainWindow.FLAG_CACHE_PREFIX + SpaceInfo.FactionId,
                       new xna.Vector2(
                           _mapUI._cvLayerPosition.X + _space.CentreX - MainWindow.FLAG_WIDTH / 2,
                           _mapUI._cvLayerPosition.Y + _space.CentreY - MainWindow.FLAG_HEIGHT - 4));
                }
            }
        }
        #endregion

        #region MaskLine
        public enum MaskLineStyle
        {
            WHITE = 0,
            ORANGE = 1,
            LINE_ANIM = 2
        }

        public class MaskLine : IDisposable
        {
            public double Per
            {
                get { return _per; }
                set
                {
                    _per = Math.Max(0, Math.Min(100, value));
                    if (_per != _lastPer)
                    {
                        _cvRoot.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            UpdatePer();
                        }));
                    }
                    _lastPer = _per;
                }
            }

            MapUI _mapUI = null;
            MaskLineStyle _style;
            Point[] _points = null;
            List<double[]> _stepList = new List<double[]>();
            List<Line[]> _lineList = new List<Line[]>();
            double _stepPer = 0;
            double _per = 0;
            double _lastPer = 0;
            Canvas _cvRoot = new Canvas();

            public MaskLine(MapUI mapUI, MaskLineStyle style, Point start, Point end)
                : this(mapUI, style, new Point[] { start, end })
            {
            }

            public MaskLine(MapUI mapUI, MaskLineStyle style, Point[] points)
            {
                _mapUI = mapUI;
                _style = style;
                _points = points;
                _stepPer = 100d / _points.Length - 1;

                var path = new Path
                {
                    Stroke = new SolidColorBrush(Color2.White(30)),
                    StrokeThickness = 8
                };
                _cvRoot.Children.Add(path);

                #region geometry
                var geometry = new StreamGeometry { FillRule = FillRule.EvenOdd };
                using (var ctx = geometry.Open())
                {
                    for (int i = 0, len = _points.Length; i < len; i++)
                    {
                        var point = _points[i];
                        if (i == 0)
                        {
                            ctx.BeginFigure(point, false, false);
                        }
                        else
                        {
                            ctx.LineTo(point, true, true);
                        }
                        //var br = new Border
                        //{
                        //    Width = 8,
                        //    Height = 8,
                        //    CornerRadius = new CornerRadius(8),
                        //    BorderBrush = new SolidColorBrush(Color2.White(50)),
                        //    BorderThickness = new Thickness(1)
                        //};
                        //br.SetLeftTop(point.X - br.Width / 2, point.Y - br.Width / 2);
                        //_cvRoot.Children.Add(br);
                    }
                }
                #endregion

                path.Data = geometry;

                var prev = new Point();
                for (int i = 0, len = _points.Length; i < len; i++)
                {
                    var curr = _points[i];
                    if (i > 0)
                    {
                        double cx = (curr.X - prev.X) / _stepPer, cy = (curr.Y - prev.Y) / _stepPer;
                        _stepList.Add(new double[] { prev.X, prev.Y, curr.X, curr.Y, cx, cy });

                        var lineList = new List<Line>();
                        lineList.Add(AddLine(Color2.Orange(50), 8));
                        lineList.Add(AddLine(Color2.Yellow(30), 6));
                        lineList.Add(AddLine(Color2.White(80), 2));
                        _lineList.Add(lineList.ToArray());
                    }
                    prev = curr;
                }

                _mapUI._cvCacheLayerMask.Children.Add(_cvRoot);
            }

            Line AddLine(Color color, double strokeThickness)
            {
                var line = new Line
                {
                    StrokeThickness = strokeThickness,
                    Stroke = new SolidColorBrush(color),
                    Visibility = Visibility.Collapsed
                };
                _cvRoot.Children.Add(line);
                return line;
            }
            void UpdatePer()
            {
                var d = _per / _stepPer;
                var c = Math.Floor(d);
                for (int i = 0, len = _stepList.Count; i < len; i++)
                {
                    var step = _stepList[i];
                    var lines = _lineList[i];
                    foreach (var line in lines)
                    {
                        line.X1 = step[0];
                        line.Y1 = step[1];
                    }
                    var cc = _per - c * _stepPer;
                    if (i < c)
                    {
                        #region full
                        foreach (var line in lines)
                        {
                            line.X2 = step[2];
                            line.Y2 = step[3];
                            line.Visibility = Visibility.Visible;
                        }
                        #endregion
                    }
                    else if (c - i == 0 && cc > 0)
                    {
                        #region <full
                        foreach (var line in lines)
                        {
                            line.X2 = line.X1 + cc * step[4];
                            line.Y2 = line.Y1 + cc * step[5];
                            line.Visibility = Visibility.Visible;
                        }
                        #endregion
                    }
                    else
                    {
                        #region >full
                        foreach (var line in lines)
                        {
                            line.Visibility = Visibility.Collapsed;
                        }
                        #endregion
                    }
                }
            }

            public void Dispose()
            {
                _mapUI._cvCacheLayerMask.Children.Remove(_cvRoot);
            }
        }
        #endregion

        #region LAYER
        public const int LAYER_BG = 0;
        public const int LAYER_FILL = 1;
        public const int LAYER_STROKE = 2;
        public const int LAYER_FIRE = 3;
        public const int LAYER_PEOPLE = 4;
        public const int LAYER_FLAG = 5;
        public const int LAYER_LABEL = 6;
        public const int LAYER_BLOCK = 7;
        #endregion

        const int MASK_UPDATE_INTERVAL = 200;
        const string MASK_LINE_HOER_MOVE = "HERO_MOVE";

        public bool StopEvent
        {
            get { return true; }
        }

        #region field
        string _areaId = null;
        Dictionary<string, Block> _blockDic = new Dictionary<string, Block>();
        Block[,] _blocks = null;
        int _aWidth = 0, _aHeight = 0;
        List<Block> _factionBlockList = new List<Block>();
        Dictionary<string, MaskLine> _maskLineDic = new Dictionary<string, MaskLine>();

        BitmapImage _bitmapPeople = null;
        BitmapImage _bitmapMonster = null;
        BitmapImage _bitmapFire = null;

        CacheDrawCanvas _cacheLayer = null;
        CacheDrawCanvas _cacheLayerFront = null;
        CacheDrawCanvas _cacheLayerMask = null;
        CacheDrawCanvas _cacheBlock = null;
        CacheDrawCanvas _cacheName = null;
        DrawFrame _frameBlock = new DrawFrame();
        DrawFrame _frameName = new DrawFrame();
        bool _canDraw = false;
        xna.Vector2 _cvLayerPosition;

        Image _imageHeroLabel = null;
        Point? _myHeroPosition = null;
        Point? _lastMyHeroPosition = null;

        Canvas _cvCahceLayer = new Canvas();
        Canvas _cvCacheLayerFront = new Canvas();
        Canvas _cvCacheLayerMask = new Canvas();
        comm.Timing _timingMask = new comm.Timing();
        int _maskLineCount = -1;
        #endregion

        public MapUI()
        {
            InitializeComponent();

            #region _bitmaps
            _bitmapPeople = new BitmapImage();
            _bitmapPeople.FromFile("gui2/icon/icon005.png");

            _bitmapMonster = new BitmapImage();
            _bitmapMonster.FromFile("gui2/icon/icon001.png");

            _bitmapFire = new BitmapImage();
            _bitmapFire.FromFile("gui2/icon/icon004.png");
            #endregion

            _cacheLayer = MainGame.MainWindow.CreateCacheCanvas();
            _cacheLayerFront = MainGame.MainWindow.CreateCacheCanvas();
            _cacheBlock = MainGame.MainWindow.CreateCacheCanvas();
            _cacheName = MainGame.MainWindow.CreateCacheCanvas();

            _cacheLayerMask = MainGame.MainWindow.CreateCacheCanvas();
            _cacheLayerMask.AddElement(_cvCacheLayerMask);

            for (int i = 0, len = GetLayerCount(); i < len; i++)
            {
                var cv = new Canvas { Background = new SolidColorBrush(Color2.Transparent()) };
                _cvCahceLayer.Children.Add(cv);
            }
            _cacheLayer.AddElement(_cvCahceLayer);

            #region _imageHeroLabel
            var bitmap = new BitmapImage();
            bitmap.FromFile("gui2/icon/icon002.png");
            _imageHeroLabel = new Image
            {
                Source = bitmap,
                Width = bitmap.PixelWidth,
                Height = bitmap.PixelHeight,
                Visibility = Visibility.Collapsed
            };
            _cvCacheLayerFront.Children.Add(_imageHeroLabel);
            #endregion
            _cacheLayerFront.AddElement(_cvCacheLayerFront);

            btnBack.Click += new RoutedEventHandler((o, e2) => { Hide(); });
        }

        void Fill()
        {
            var starData = MainGame.MainSpace.DStarData;
            spArea.Children.Clear();

            RadioButton1 first = null;
            foreach (var areaId in starData.AreaDic.Keys)
            {
                var area = starData.AreaDic[areaId];
                var areaId2 = areaId;
                var radio = new RadioButton1
                {
                    GroupName = "area",
                    Text = areaId,
                    Margin = new Thickness(0, 0, 0, 4),
                    VerticalAlignment = VerticalAlignment.Center,
                    Foreground = new SolidColorBrush(Color2.White())
                };
                if (first == null)
                {
                    first = radio;
                }
                radio.Checked += new RoutedEventHandler((o, e) =>
                {
                    _areaId = areaId2;
                    FillBlock();
                });
                spArea.Children.Add(radio);
            }
            if (first != null)
            {
                first.IsChecked = true;
            }
        }
        void FillBlock()
        {
            _canDraw = false;
            var starData = MainGame.MainSpace.DStarData;
            var area = starData.AreaDic[_areaId];
            _aWidth = area.Width;
            _aHeight = area.Height;

            _blocks = new Block[area.Width, area.Height];
            _blockDic.Clear();

            ClearMaskLine();

            cvLayer.Children.Clear();

            _cacheBlock.ClearElement();
            _cacheName.ClearElement();

            int lw = _aWidth * area.MapSize, lh = _aHeight * area.MapSize;

            cvLayer.Width = lw;
            cvLayer.Height = lh;
            cvLayer.SetRectClip();

            _cvCahceLayer.Width = lw;
            _cvCahceLayer.Height = lh;
            _cvCahceLayer.SetRectClip();

            _cvCacheLayerFront.Width = lw;
            _cvCacheLayerFront.Height = lh;
            _cvCacheLayerFront.SetRectClip();

            _cvCacheLayerMask.Width = lw;
            _cvCacheLayerMask.Height = lh;
            _cvCacheLayerMask.SetRectClip();

            for (int i = 0, len = GetLayerCount(); i < len; i++)
            {
                var cv = GetLayer(i);
                cv.Width = _cvCahceLayer.Width;
                cv.Height = _cvCahceLayer.Height;
                if (i != LAYER_LABEL)
                {
                    cv.Children.Clear();
                }
            }

            #region bg
            if (area.BGImageBytes != null)
            {
                var bitmap = new BitmapImage();
                bitmap.FromBytes(area.BGImageBytes);
                GetLayer(LAYER_BG).Children.Add(new Image
                {
                    Source = bitmap,
                    Width = bitmap.PixelWidth,
                    Height = bitmap.PixelHeight
                });
            }
            #endregion

            #region blocks
            for (int x = 0; x < area.Width; x++)
            {
                for (int y = 0; y < area.Height; y++)
                {
                    var space = area.Spaces[x, y];
                    var block = new Block(this, x, y, space);
                    _blocks[x, y] = block;
                    _blockDic.Add(MainGame.MainSpace.DStar.ToRealSpaceId(space.SpaceId), block);
                    cvLayer.Children.Add(block);
                }
            }
            #endregion

            _canDraw = true;

            LoadSpaceInfo();
        }
        void LoadSpaceInfo()
        {
            TcpClient.Call<comm.objst.SpaceInfo[]>(comm.objst.TcpMessageType.ToServerGetStarSpaceList, new string[] { MainGame.MainSpace.StarId, _areaId }, (spaceInfos, message) =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    _factionBlockList.Clear();
                    GetLayer(LAYER_FLAG).Children.Clear();

                    foreach (var info in spaceInfos)
                    {
                        if (_blockDic.ContainsKey(info.SpaceId))
                        {
                            _blockDic[info.SpaceId].FillSpaceInfo(info);
                        }
                    }
                    _cacheLayer.BeginDraw();
                    this.UpBeginDraw();
                }));
            });
        }

        Canvas GetLayer(int layer)
        {
            return (Canvas)_cvCahceLayer.Children[layer];
        }
        int GetLayerCount()
        {
            var fields = GetType().GetFields();
            var count = 0;
            foreach (var fd in fields)
            {
                if (fd.Name.IndexOf("LAYER_") == 0)
                {
                    count++;
                }
            }
            return count;
        }

        Block GetMyHeroAtBlock()
        {
            Block obj;
            _blockDic.TryGetValue(MainGame.MainSpace.SpaceId, out obj);
            return obj;
        }

        void MyHeroMoveTo(Block block)
        {
            RemoveMaskLine(MASK_LINE_HOER_MOVE);

            var fromBlock = GetMyHeroAtBlock();
            if (fromBlock != null && fromBlock != block)
            {
                var astar = new comm.AStar(false);
                var ns = astar.Find(1, _aWidth, _aHeight, fromBlock.BlockX, fromBlock.BlockY, block.BlockX, block.BlockY, CheckPath1);
                if (ns.Length == 0)
                {
                    ns = astar.Find(1, _aWidth, _aHeight, fromBlock.BlockX, fromBlock.BlockY, block.BlockX, block.BlockY, CheckPath2);
                }
                if (ns.Length > 1)
                {
                    var list = new List<Point>();
                    foreach (var n in ns)
                    {
                        var b = _blocks[n.X, n.Y];
                        list.Add(new Point(b.Centre.X, b.Centre.Y));
                    }
                    AddMaskLine(MASK_LINE_HOER_MOVE, MaskLineStyle.WHITE, list.ToArray());
                }
            }
        }
        bool CheckPath1(int x, int y, int pathSize)
        {
            if (new Rect(0, 0, _aWidth - 1, _aHeight - 1).Contains(x, y))
            {
                var block = _blocks[x, y];
                return block.SpaceInfo.State == comm.objst.SpaceState.WAR_END &&
                    (block.SpaceInfo.OccupyType == comm.objst.SpaceOccupyType.EMPTY ||
                    block.SpaceInfo.OccupyType == comm.objst.SpaceOccupyType.FAC);
            }
            return false;
        }
        bool CheckPath2(int x, int y, int pathSize)
        {
            return false;
        }

        void AddMaskLine(string key, MaskLineStyle style, Point[] points)
        {
            _maskLineDic.Add(key, new MaskLine(this, style, points));
        }
        void RemoveMaskLine(string key)
        {
            if (_maskLineDic.ContainsKey(key))
            {
                _maskLineDic[key].Dispose();
                _maskLineDic.Remove(key);
            }
            _cacheLayerMask.BeginDraw();
        }
        void ClearMaskLine()
        {
            foreach (var item in _maskLineDic.Values)
            {
                item.Dispose();
            }
            _maskLineDic.Clear();
            _cacheLayerMask.BeginDraw();
        }
        MaskLine GetMaskLine(string key)
        {
            MaskLine obj;
            _maskLineDic.TryGetValue(key, out obj);
            return obj;
        }

        void BlockMouseEvent(MouseEventType type, Point point, Block block)
        {
            if (type == MouseEventType.MOVE)
            {
                _frameName.Display = true;
                _frameName.SetFrame(_cacheName, block.SpaceId, new xna.Vector2((int)point.X + 20, (int)point.Y + 10));
            }
            else if (type == MouseEventType.LEFT_DOWN || type == MouseEventType.RIGHT_DOWN)
            {
                _frameBlock.SetFrame(_cacheBlock, block.SpaceId, new xna.Vector2(block.Position.X + _cvLayerPosition.X, block.Position.Y + _cvLayerPosition.Y));

                if (type == MouseEventType.RIGHT_DOWN)
                {
                    MyHeroMoveTo(block);
                }
            }
        }

        public void CallMouseEvent(MouseEventType type, Point point)
        {
            _frameName.Display = false;
        }
        public void Show()
        {
            MainGame.Debug = false;
            _canDraw = true;
            this.UpDisplay(true);
            Fill();
        }
        public void Hide()
        {
            MainGame.Debug = true;
            _canDraw = false;
            this.UpDisplay(false);
            _frameBlock.Display = false;
            _frameName.Display = false;
        }

        public void Update(comm.TimeStat timeStat)
        {
            if (_canDraw)
            {
                _cvLayerPosition = MainGame.MainWindow.GetOffset(cvLayer);

                #region _myHeroPosition
                var block = GetMyHeroAtBlock();
                if (block != null)
                {
                    _myHeroPosition = new Point(block.Centre.X, block.Centre.Y);
                    _imageHeroLabel.SetLeftTop(_myHeroPosition.Value.X - 11 + 10, _myHeroPosition.Value.Y - 31);
                    _imageHeroLabel.Visibility = Visibility.Visible;
                }
                else
                {
                    _myHeroPosition = null;
                    _imageHeroLabel.Visibility = Visibility.Collapsed;
                }
                if (_lastMyHeroPosition != _myHeroPosition)
                {
                    _cacheLayerFront.BeginDraw();
                }

                _lastMyHeroPosition = _myHeroPosition;
                #endregion

                if (_maskLineDic.Count > 0 && _timingMask.GetElapsedTime(timeStat, MASK_UPDATE_INTERVAL) > 0)
                {
                    var l = GetMaskLine(MASK_LINE_HOER_MOVE);
                    if (l != null)
                    {
                        l.Per += 2;
                    }
                    _cacheLayerMask.BeginDraw();
                }
            }
        }
        public void Draw(comm.TimeStat timeStat, xnaGraphics.SpriteBatch spriteBatch)
        {
            if (_canDraw)
            {
                _cacheLayer.Draw(spriteBatch, _cvLayerPosition);
                _frameBlock.Draw(spriteBatch);
                for (int x = 0; x < _aWidth; x++)
                {
                    for (int y = 0; y < _aHeight; y++)
                    {
                        _blocks[x, y].Draw(spriteBatch);
                    }
                }
                _cacheLayerFront.Draw(spriteBatch, _cvLayerPosition);
                _cacheLayerMask.Draw(spriteBatch, _cvLayerPosition);
                _frameName.Draw(spriteBatch);
            }
        }
    }
}
